﻿#define _CRT_SECURE_NO_WARNINGS
#include "contact.h"
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
void InitContact(Contact* pc)
{
	pc->sz = 0;
	PeoInfo* ptr = (PeoInfo*)calloc(DEFAULT_SZ, sizeof(PeoInfo));
	if (ptr == NULL)
	{
		perror("InitContact");
		return;
	}
	pc->date = ptr;
	pc->capicity = DEFAULT_SZ;

	LoadcContact(pc);

}
void Check_capacity(Contact* pc)
 {
	if (pc->sz == pc->capicity)
	{
		PeoInfo* ptr=(PeoInfo*)realloc(pc->date, (pc->capicity + INC_SZ) * sizeof(PeoInfo));
		if (ptr == NULL)
		{
			perror("Check_capacity");
			return;
		}
		pc->date = ptr;
		pc->capicity += INC_SZ;
		printf("增容成功\n");
	}

  }

void Destory_capacity(Contact* pc)
{
	free(pc->date);
	pc->date = NULL;
	pc->capicity = 0;
	pc->sz = 0;
	pc = NULL;
		
}


void AddContact(Contact* pc)
{
	Check_capacity(pc);
	printf("请输入名字:");
	scanf("%s", pc->date[pc->sz].name);
	printf("请输入年龄:");
	scanf("%d", &(pc->date[pc->sz].age));
	printf("请输入性别:");
	scanf("%s", pc->date[pc->sz].sex);
	printf("请输入地址:");
	scanf("%s", pc->date[pc->sz].adress);
	printf("请输入电话:");
	scanf("%s", pc->date[pc->sz].phone);

	pc->sz++;
}

void ShowContact(const Contact* pc)
{
	int i = 0;
	printf("%-20s\t%-4s\t%-5s\t%-20s\t%-12s\n","名字","年龄","性别","地址","电话号码");
	for (i = 0; i < pc->sz; i++)
	{
		printf("%-20s\t%-4d\t%-5s\t%-20s\t%-12s\n", pc->date[i].name, pc->date[i].age, pc->date[i].sex, pc->date[i].adress, pc->date[i].phone);
	}
}

int FindName(const Contact* pc, char name[])
{
	int i = 0;
	for (i = 0; i < pc->sz; i++)
	{
		if (strcmp(pc->date[i].name, name) == 0);
		{
			
			return i;
		}
	}
	return -1;
}

void DelContact(Contact* pc)
{
	
	char name[name_max] = { 0 };
	int i = 0;
	if (pc->sz == 0)
	{
		printf("没有通讯录记录\n");
		return;
	}
		printf("请输入要删除的名字:");
		scanf("%s", name);
		int ret = FindName(pc, name);
		for (i = ret; i < pc->sz - 1; i++)
		{
			pc->date[i] = pc->date[i + 1];
		}
		pc->sz--;
		printf("删除成功");
}


void SerchContact(const Contact* pc)
{
	printf("请输入要查找人的姓名:");
	char name[name_max] = { 0 };
	scanf("%s", name);
	int ret = FindName(pc, name);
	int i = ret;
	
	
	printf("%-20s\t%-4d\t%-5s\t%-20s\t%-12s\n", pc->date[i].name, pc->date[i].age, pc->date[i].sex, pc->date[i].adress, pc->date[i].phone);


}

void SaveContact(Contact* pc)
{
	FILE* pf = fopen("contact.txt", "wb");
	if (pf == NULL)
	{
		perror("SaveContact");
	}
	else
	{
		int i = 0;
		for (i = 0; i < pc->sz; i++)
		{
			fwrite(pc->date + i, sizeof(PeoInfo), 1, pf);
		}

		fclose(pf);
		pf = NULL;
	}
}

void LoadcContact(Contact* pc)
{
	int i = 0;
	FILE* pf = fopen("contact.txt", "r");
	if (pf== NULL)
	{
		perror("LoadcContact");
	}
	else
	{
		PeoInfo tmp = { 0 };
		while(fread(&tmp, sizeof(PeoInfo), 1, pf))
		{
			Check_capacity(pc);

			pc->date[i] = tmp;
			pc->sz++;
			i++;
		}

		fclose(pf);
		pf = NULL;
	}


}